# encoding: utf-8
"""
后台操作
"""
from django.http import HttpResponse
from wxxiaohello.models import Blog,Classify,Tag,Comment
from django.template import loader,Context
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt

from  datetime  import  date  
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger
from django.core.paginator import EmptyPage
from wxxiaohello.settings import PAGE_SIZE
from django.core.cache import cache
from django.shortcuts import render

'''控制台首页'''
@login_required
def edit(request):
    return render(request, "edit/edit.html")

"""
跳转新建文章页面- 带文章分组类别信息
"""
@login_required
def  create_new_blog(request):

    classifys = Classify.objects.all();

    return render_to_response("edit/create_new_blog.html",{"active":"create_new_blog","classifys":classifys}) 

"""
保存新建得文章 （草稿 ）文章信息
"""
@login_required
@csrf_exempt
def save_new_blog(request):
    user = request.user
    title = request.POST['title']
    summary = request.POST['summary']
    content = request.POST['content']
    tags = request.POST['tags']
    classify_id = request.POST['classify_id']
    rtype = request.POST['type']
    release = request.POST['release']
    
    blog = Blog.objects.create(user_id = user.id,title=title,summary = summary,content = content,type=rtype,release=release,time=date.today(),classify_id=classify_id)
    blog.save()
    ## 处理关键字 tag
    tags = " ".join(tags.split())
    if tags!=" " and len(tags)>0:  
        tags = tags.lstrip().rstrip().split(" ")
        for tc in tags:
            try:
                #已经存在的tag
                tag = Tag.objects.get(content=tc)
                blog.tag.add(tag)
            except:
                #新建立tag
                tag = Tag.objects.create(content=tc)
                tag.save()
                blog.tag.add(tag)
    
    return HttpResponse("success")

"""
获取需要修改的文章信息
"""
@login_required
def get_edit_blog(request,blog_id):
    blog = Blog.objects.get(id = blog_id)
    tags = blog.tag.all()
    classifys = Classify.objects.all();
    active = "get_edit_blog_r"
    if blog.release==0:
        active = "get_edit_blog_d"
    context = Context({
                       "blog":blog,
                       "tags":tags,
                       "classifys":classifys,
                       "active":active,
                       })
    template  = loader.get_template("edit/get_edit_blog.html")
    return HttpResponse(template.render(context))


"""
保存修改后的文章信息
"""
@csrf_exempt
@login_required
def save_update_blog(request):
    rid = request.POST["id"]
    title = request.POST['title']
    summary = request.POST['summary']
    content = request.POST['content']
    tags = request.POST['tags']
    classify_id = request.POST['classify_id']
    rtype = request.POST['type']
    release = request.POST['release']
    
    blog = Blog.objects.get(id=rid)
    blog.title = title
    blog.summary = summary
    blog.content = content
    blog.type = rtype
    blog.release = release
    blog.classify_id = classify_id
    
    if(blog.release ==0 and release==1):
        blog.time=date.today()
    blog.save()
    
    ### 处理 Tag, 去除原有的tag
    blog.tag.remove()
    
    ## 处理关键字 tag
    tags = " ".join(tags.split())
    if tags!=" " and len(tags)>0:  
        tags = tags.lstrip().rstrip().split(" ")
        for tc in tags:
            try:
                #已经存在的tag
                tag = Tag.objects.get(content=tc)
                blog.tag.add(tag)
            except:
                #新建立tag
                tag = Tag.objects.create(content=tc)
                tag.save()
                blog.tag.add(tag)
    return HttpResponse("success")

"""
获取已发布文章列表
"""
@csrf_exempt
@login_required
def get_released_blog_list(request):
        
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(release=1).order_by("-id")
    paginator  = Paginator(blogs,PAGE_SIZE)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
     
    context = Context({
                       "blog_list":blog_list,
                       "active":"get_released_blog_list",
                       "query":"/edit/get_released_blog_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_blog_list.html")
    return HttpResponse(template.render(context))

"""
获取草稿文章列表
"""
@login_required
def get_draft_blog_list(request):
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(release=0).order_by("-id")
    paginator  = Paginator(blogs,PAGE_SIZE)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
        
    context = Context({
                       "blog_list":blog_list,
                       "active":"get_draft_blog_list",
                       "query":"/edit/get_draft_blog_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_blog_list.html")
    return HttpResponse(template.render(context))

"""
删除文章 - 根据id删除
"""
@csrf_exempt
@login_required
def delete_blog(request):
    rid = request.POST["id"]
    blog = Blog.objects.get(id=rid)
    blog.tag.remove()
    blog.delete()
    return HttpResponse("success")
 
"""
获取文章分组（分类）列表
"""
@csrf_exempt
@login_required
def get_classify_list(request):

    classify_list = Classify.objects.all()
    context = Context({
                       "classify_list":classify_list,
                       "active":"get_classify_list",
                       })
    
    template  = loader.get_template("edit/get_classify_list.html")
    return HttpResponse(template.render(context))

"""
删除一个文章分类- 根据id删除
"""
@csrf_exempt
@login_required
def delete_classify(request):
    rid = request.POST["id"]
    classify = Classify.objects.get(id=rid)
    blogs = Blog.objects.filter(classify_id=rid)
    if len(blogs) >0:
        for blog in blogs:
            blog.classify_id = 1
            blog.save()
    if(rid>1):
        classify.delete()
    return HttpResponse("success")

"""
新增文章分类信息
"""
@csrf_exempt
@login_required
def add_classify(request):

    content = request.POST["content"]
    classify = Classify.objects.create()
    classify.content = content
    
    classify.save()
    return HttpResponse("success")

"""
修改文章分类信息 - 根据id
"""
@csrf_exempt
@login_required
def update_classify(request):
    
    rid = request.POST["id"]
    content = request.POST["content"]
    classify = Classify.objects.get(id=rid)
    classify.content = content
    
    classify.save()
    return HttpResponse("success")

"""
获取留言列表 - 根据id删除
"""
@csrf_exempt
@login_required
def get_message_list(request):

    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    comments = Comment.objects.all().order_by("-id")
    paginator  = Paginator(comments,PAGE_SIZE)
    try:
        comment_list = paginator.page(pn)
    except PageNotAnInteger:
        comment_list = paginator.page(1)
    except EmptyPage:
        comment_list = paginator.page(paginator.num_pages)
        
    context = Context({
                       "comment_list":comment_list,
                       "active":"get_message_list",
                       "query":"/edit/get_message_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_message_list.html")
    return HttpResponse(template.render(context))
    
"""
删除某一条留言 - 根据id删除
"""
@csrf_exempt
@login_required
def delete_message(request):
    rid = request.POST["id"]
    comment = Comment.objects.get(id=rid)
    comment.delete()
    return HttpResponse("success")

"""
用户留言 - 新增一条留言记录
"""
@csrf_exempt
def add_message(request):
    blog_id = request.POST["blog_id"]
    name = request.POST["name"]
    website = request.POST["website"]
                                         
    message = request.POST["message"]
    time = date.today()
    
    comment = Comment.objects.create()

    comment.blog_id=blog_id
    comment.name = name
    if(website and "http://" in website):
        comment.website = website
    comment.message = message
    comment.time = time
    comment.save()
    return HttpResponse("success")

@login_required
def clear_cache(request):
    cache.clear()
    context = Context({
                   "message":"缓存清除成功！",
                   })
    return render(request, "edit/edit.html",context)